package com.erpanderp.wam.adm.model.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.Session;
import com.erpanderp.wam.adm.model.entity.Module;
import com.erpanderp.wam.util.HibernateUtil;

public class WAMUserModuleEngine {

	public List<Module> getUserModules(String employeeCode){
		List<Module> modules = new ArrayList<Module>();
		try {
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			String queryString = "select distinct rsg.serviceGroup.module from RoleServiceGroup rsg where rsg.role.roleId in (select er.role.roleId from EmployeeRole er where er.employee.employeeCode = :employeeCode)";
			Query query = session.createQuery(queryString).setParameter("employeeCode", employeeCode);
			query.setCacheable(false);
			Set<Module> modulesSet = new HashSet<Module>();
			modulesSet.addAll(query.list());
			
			queryString = "select distinct rs.service.module from RoleService rs where rs.role.roleId in (select er.role.roleId from EmployeeRole er where er.employee.employeeCode = :employeeCode)";
			query = session.createQuery(queryString).setParameter("employeeCode", employeeCode);
			query.setCacheable(false);
			modulesSet.addAll(query.list());
			
			modules.addAll(modulesSet);
			for(Module module : modules){
				System.out.println(module.getModuleName());
			}
			session.getTransaction().commit();
			return modules;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}	
	}
	
	public static void main(String a[]){
		new WAMUserModuleEngine().getUserModules("E50001");
	}
}
